<?php

namespace App\Console\Commands;

use App\Models\User\User;
use Illuminate\Console\Command;
use App\Models\User\DAU;
use Illuminate\Support\Facades\DB;

class DauSave extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:dau';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $yesterday = date("Y-m-d", time() - 3600*24);
        $result = User::select(DB::raw("COUNT(1) AS c, SPID AS spid"))
        ->where("LastLogonDate", ">=", $yesterday . " 06:00:00")
        ->groupBy("SPID")
        ->get();

        foreach ($result as $val) {
            $Dau = new DAU();
            $Dau->num  = $val->c;
            $Dau->time = $yesterday;
            $Dau->spid = $val->spid;
            $Dau->save();
        }
    }
}
